package com.dezheyun.dezheshop.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dezheyun.common.utils.PageUtils;
import com.dezheyun.common.utils.Query;

import com.dezheyun.dezheshop.product.dao.CategoryDao;
import com.dezheyun.dezheshop.product.entity.CategoryEntity;
import com.dezheyun.dezheshop.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> entityList = this.baseMapper.selectList(null);
        //组成父子的树形结构
        //1.找到所有的 1级分类
        List<CategoryEntity> oneMenus = entityList.stream()
                .filter((c) -> c.getParentCid() == 0)
                .map(menus->{
                  menus.setChildren(getChildren(menus,entityList));
                  return menus;
                })
                .sorted((menu1,menu2)-> (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()))
                .collect(Collectors.toList());
        return oneMenus;
    }

    @Override
    public void removeMenuByIds(List<Long> ids) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用了，引用了不能删
        //真正开发中，一般用逻辑删除（用数据库中的某个字段作为标识位，是否被删除）

        //批量删除
        this.baseMapper.deleteBatchIds(ids);
    }

    /**
     * 查询子分类的数据
     */
    private List<CategoryEntity> getChildren(CategoryEntity entity,List<CategoryEntity> all){
        return all.stream()
                .filter(c -> c.getParentCid().equals(entity.getCatId()))
                .map(menus->{
                    menus.setChildren(getChildren(menus,all));
                    return menus;
                })
                .sorted((menu1,menu2)-> (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort()))
                .collect(Collectors.toList());
    }

}